import { BaseResponse } from '@/common/BaseResponse';
import { User } from '@/entity/user.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PageParamDto } from './dto/page-param.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  async userListSelect(pageParamDto: PageParamDto) {
    const qb = this.userRepository.createQueryBuilder('users');
    let result = qb;
    if (pageParamDto.id) {
      result = qb.andWhere('users.id = :id', {
        id: pageParamDto.id,
      });
    }

    if (pageParamDto.nickName) {
      result = qb.andWhere(`users.nick_name like '%${pageParamDto.nickName}%'`);
    }

    result
      .limit(pageParamDto.size)
      .offset((pageParamDto.page - 1) * pageParamDto.size);
    const total = await result.getCount();
    const list = await result.getMany();

    return BaseResponse.toSuccesJustData({
      page: Number(pageParamDto.page),
      list,
      size: Number(pageParamDto.size),
      total,
    });
  }

  deleteUser(id: number) {
    return this.userRepository.delete(id);
  }
}
